<template>
  <div style="height: 90px;display: flex;align-items: center">
    <img src="@/assets/icon/blog-t.png" style="height: 60px;margin: 15px;">
    <!--<span style="font-weight: bolder;font-size: 1.5em;padding-left: 15px;">DanTou Blog</span>-->
  </div>
  <el-row class="el-row" justify="center">
    <el-col :xl="5" :lg="6" :md="9" :sm="11">
      <!--<h2 style="font-weight: bolder">DanTou Blog</h2><br>-->
      <img src="@/assets/icon/login.png" style="height: 180px;margin-bottom: 20px">
      <p>合抱之木，生于毫末</p><br>
      <p>百丈之台，起于垒土；千里之行，始于足下</p><br>
    </el-col>
    <el-col :span="1">
      <el-divider direction="vertical"></el-divider>
    </el-col>
    <el-col :xl="5" :lg="6" :md="9" :sm="11">
      <h2 style="width: 400px;">用户登录</h2><br>
      <el-form ref="ruleFormRef"
               :model="ruleForm"
               :rules="rules"
               label-width="100px">
        <el-form-item label="用户名" prop="username" style="width: 400px;">
          <el-input v-model="ruleForm.username" type="text" maxlength="12" show-word-limit clearable/>
        </el-form-item>
        <el-form-item label="密&nbsp;&nbsp;&nbsp;&nbsp;码" prop="password" style="width: 400px;">
          <el-input v-model="ruleForm.password" type="password" :show-password="true" clearable/>
        </el-form-item>
        <el-form-item label="验证码" prop="captchaCode" style="width: 400px;">
          <el-input v-model="ruleForm.captchaCode" style="width: 150px;float: left" clearable @keydown.enter="submitForm"/>
          <el-image :src="kaptchaSrc" class="captchaImg" @click="getNewKaptcha"></el-image>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">登录
          </el-button>
          <el-button @click="resetForm()">重置</el-button>
          <!--          <el-button @click="getCode()">验证码</el-button>-->

          <!--<el-button @click="testToken()">测试错误Token</el-button>-->
        </el-form-item>
        <el-form-item>
          <el-link type="info" @click="toRegister">没有账号？转去注册</el-link>
          <el-link type="info" @click="forgetPasswd" style="margin-left: 50px">忘记密码</el-link>
        </el-form-item>
      </el-form>
      <el-divider border-style="dashed">三方账号登录</el-divider>
      <div>
        <el-avatar size="small"
                   src="/icon/gitee.jpeg"
                   @click="otherLogin('gitee')"
        />
        <el-avatar size="small"
                   src="/icon/baidu.ico"
                   @click="otherLogin('baidu')"
        />
        <!--        qq 应用审核未通过,域名需要备案,以后再开发-->
        <!--        <el-avatar size="small"-->
        <!--                   src="/icon/qq.png"-->
        <!--                   @click="otherLogin('qq')"-->
        <!--        />-->
      </div>
    </el-col>
  </el-row>
</template>

<script>
import {ElMessage} from "element-plus";
import userStore from "@/store/UserStore";
import pinia from "@/store/pinia";
import loginStore from "@/store/loginStore";

const store = userStore(pinia);
const storeLogin = loginStore(pinia);

export default {
  name: "Login",
  data() {
    return {
      store,
      storeLogin,
      kaptchaSrc: "/api/kaptcha",
      ruleForm: {
        username: '',
        password: '',
        captchaCode: '',
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 5, max: 12, message: '用户名长度应该在5-12位', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 24, message: '密码长度应该在6-24位', trigger: 'blur'},
        ],
        captchaCode: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {min: 5, max: 5, message: '验证码长度应该在5位字母或数字', trigger: 'blur'},
        ],

      }
    }
  },
  methods: {
    submitForm: function () {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (valid) {
          let {data: result} = await this.$http.post("/api/login/login", this.ruleForm)
          // console.log(result)
          window.sessionStorage.setItem("userInfo", JSON.stringify(result.dataMap.userInfo))
          window.sessionStorage.setItem("token", JSON.stringify(result.dataMap.token))
          // 如果code == 200，保存数据，转到index
          if (result.code === 200) {
            ElMessage.success({showClose: true, message: "登录成功！"})
            this.store.updateToken(result.dataMap.token)
            this.store.updateUserInfo(result.dataMap.userInfo)
            // console.log(this.store.userInfo)
            // 如果有页面跳转，跳转到指定页面，否则跳转到首页
            const nextPath = this.storeLogin.getNextPath
            if (nextPath) {
              // 如果有name属性，跳转name
              if (nextPath.name) {
                this.storeLogin.setNextPath(null)
                this.$router.push({name: nextPath.name, params: nextPath.params})
              } else {
                // 否则跳转路径
                this.storeLogin.setNextPath(null)
                this.$router.push({path: nextPath.path, query: nextPath.query})
              }
            } else {
              this.$router.push({name: "index"})
            }
          } else {
            // 如果code是其他，显示错误信息
            ElMessage.error(result.msg)
          }
        } else {
          ElMessage.error("表单填写有误！")
        }
      })

    },
    resetForm() {
      this.$refs.ruleFormRef.resetFields()
    },
    async getCode() {
      let result = await this.$http.get("/api/test/getKaptchaCode")
      // console.log(result.data)
      this.ruleForm.captchaCode = result.data
    },
    getNewKaptcha() {
      this.kaptchaSrc = "/api/kaptcha?data=" + new Date()
    },
    testToken() {
      this.$http.get("/api/test/test")
    },
    toRegister() {
      this.$router.push({name: 'register'})
    },
    forgetPasswd() {
      this.$message.error("忘了就忘了吧，没有找回功能喽。 (*^__^*) 嘻嘻……")
    },
    async otherLogin(type) {
      let {data: result} = await this.$http.get("/api/login/getOauthUrl", {
        params: {
          otherType: type
        }
      })
      window.open(result.dataMap.url, "_self")
    }
  }
}
</script>

<style scoped>
.el-row {
  background-color: #fafafa;
  height: 90vh;
  display: flex;
  align-items: center;
  text-align: center;

}

.el-divider--vertical {
  height: 200px;
}

.el-divider__text.is-center {
  color: #d70606;
}

.el-avatar {
  margin-left: 5px;
  margin-right: 5px;
  border: 1px solid rgba(161, 156, 156, 0.62);
}

.captchaImg {
  float: right;
  height: 35px;
  margin-left: 10px;
  border-radius: 10px;
}
</style>